package com.xiaoxi.bms.common.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.xiaoxi.bms.common.constant.enumeration.statuscode.user.LoginUserEnums;
import com.xiaoxi.bms.common.exception.BMSSecurityException;
import com.xiaoxi.bms.common.util.AuthUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Objects;

/**
 * @ClassName MyMetaObjectHandler
 * @Description 通过 POJO类 定义 @TableField(fill = FieldFill.INSERT/UPDATE/INSERT_UPDATE) 更新或生成对应值
 * @Author xiaoxi
 * @Date 2022/4/24 15:18
 * @Version 1.0
 */
@Component
public class MyMetaObjectHandler implements MetaObjectHandler {

    @Override
    public void insertFill(MetaObject metaObject) {

        if (Objects.isNull(AuthUtils.getAuthentication())) {
            throw new BMSSecurityException(LoginUserEnums.USER_NOT_LOGIN);
        }

        // 锁
        this.setFieldValByName("version", 1L, metaObject);
        // 创建人
        this.setFieldValByName("createId", AuthUtils.getCurrentUser().getId(), metaObject);
        // 创建时间
        this.setFieldValByName("createTime", LocalDateTime.now(), metaObject);
        // 修改人
        this.setFieldValByName("modifyId", AuthUtils.getCurrentUser().getId(), metaObject);
        // 修改时间
        this.setFieldValByName("modifyTime", LocalDateTime.now(), metaObject);

    }

    @Override
    public void updateFill(MetaObject metaObject) {

        if (Objects.isNull(AuthUtils.getAuthentication())) {
            throw new BMSSecurityException(LoginUserEnums.USER_NOT_LOGIN);
        }

        // 修改人
        this.setFieldValByName("modifyId", AuthUtils.getCurrentUser().getId(), metaObject);
        // 修改时间
        this.setFieldValByName("modifyTime", LocalDateTime.now(), metaObject);

    }

}

